package com.yayun.merchant.service.impl;

import com.yayun.common.utils.DateUtils;
import com.yayun.common.utils.SecurityUtils;
import com.yayun.merchant.domain.AuctionItem;
import com.yayun.merchant.domain.AuctionRecord;
import com.yayun.merchant.domain.OmsOrder;
import com.yayun.merchant.domain.OmsOrderItem;
import com.yayun.merchant.mapper.AuctionItemMapper;
import com.yayun.merchant.mapper.AuctionRecordMapper;
import com.yayun.merchant.service.IAuctionItemService;
import com.yayun.merchant.service.IAuctionRecordService;
import com.yayun.merchant.service.IOmsOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class AuctionItemServiceImpl implements IAuctionItemService {
    @Autowired
    private AuctionItemMapper auctionItemMapper;

    @Autowired
    private IAuctionRecordService auctionRecordService;

    @Autowired
    private AuctionRecordMapper auctionRecordMapper;

    @Autowired
    private IOmsOrderService orderService;

    /**
     * 查询拍卖商品
     */
    @Override
    public AuctionItem selectAuctionItemById(Long id) {
        return auctionItemMapper.selectAuctionItemById(id);
    }

    /**
     * 查询拍卖商品列表
     */
    @Override
    public List<AuctionItem> selectAuctionItemList(AuctionItem auctionItem) {
        return auctionItemMapper.selectAuctionItemList(auctionItem);
    }

    /**
     * 新增拍卖商品
     */
    @Override
    public int insertAuctionItem(AuctionItem auctionItem) {
        auctionItem.setCreateTime(DateUtils.getNowDate());
        return auctionItemMapper.insertAuctionItem(auctionItem);
    }

    /**
     * 修改拍卖商品
     */
    @Override
    public int updateAuctionItem(AuctionItem auctionItem) {
        auctionItem.setUpdateTime(DateUtils.getNowDate());
        return auctionItemMapper.updateAuctionItem(auctionItem);
    }

    /**
     * 批量删除拍卖商品
     */
    @Override
    public int deleteAuctionItemByIds(Long[] ids) {
        return auctionItemMapper.deleteAuctionItemByIds(ids);
    }

    /**
     * 删除拍卖商品信息
     */
    @Override
    public int deleteAuctionItemById(Long id) {
        return auctionItemMapper.deleteAuctionItemById(id);
    }

    /**
     * 开始拍卖
     */
    @Override
    @Transactional
    public int startAuction(Long id) {
        AuctionItem auctionItem = new AuctionItem();
        auctionItem.setId(id);
        auctionItem.setStatus(1); // 进行中
        return updateAuctionItem(auctionItem);
    }

    /**
     * 结束拍卖
     */
    @Override
    @Transactional
    public Long endAuction(Long id) {
        // 查询最高出价记录
        AuctionRecord highestBid = auctionRecordService.selectHighestBidRecord(id);
        
        AuctionItem auctionItem = selectAuctionItemById(id);
        if (auctionItem == null) {
            throw new RuntimeException("拍卖不存在");
        }
        
        auctionItem.setStatus(2); // 已结束
        
        Long orderId = null;
        if (highestBid != null) {
            // 设置中标用户
            auctionItem.setWinnerId(highestBid.getUserId());
            // 更新竞拍记录状态
            auctionRecordService.updateAuctionRecordStatus(id, 1, 2); // 将领先改为中标
            
            // 自动生成订单
            OmsOrder order = new OmsOrder();
            order.setUserId(highestBid.getUserId());
            order.setUsername(highestBid.getUserName());
            order.setTotalAmount(highestBid.getBidPrice());
            order.setPayAmount(highestBid.getBidPrice());
            order.setStatus(0); // 待付款
            
            // 设置订单商品信息
            List<OmsOrderItem> items = new ArrayList<>();
            OmsOrderItem item = new OmsOrderItem();
            item.setProductId(auctionItem.getProductId());
            item.setProductName(auctionItem.getProduct().getName());
            item.setPic(auctionItem.getProduct().getPic());
            item.setSalePrice(highestBid.getBidPrice());
            item.setQuantity(1);
            items.add(item);
            order.setItems(items);
            
            // 创建订单
            OmsOrder createdOrder = orderService.createOrder(order);
            orderId = createdOrder.getId();
        } else {
            // 无人出价，标记为流拍
            auctionItem.setRemark("流拍");
        }
        
        updateAuctionItem(auctionItem);
        return orderId;
    }

    /**
     * 取消拍卖
     */
    @Override
    @Transactional
    public int cancelAuction(Long id) {
        AuctionItem auctionItem = new AuctionItem();
        auctionItem.setId(id);
        auctionItem.setStatus(3); // 已取消
        return updateAuctionItem(auctionItem);
    }

    /**
     * 查询进行中的拍卖
     */
    @Override
    public List<AuctionItem> selectOngoingAuctions() {
        return auctionItemMapper.selectOngoingAuctions();
    }

    /**
     * 查询即将开始的拍卖
     */
    @Override
    public List<AuctionItem> selectUpcomingAuctions() {
        return auctionItemMapper.selectUpcomingAuctions();
    }

    /**
     * 查询需要结束的拍卖
     */
    @Override
    public List<AuctionItem> selectEndingAuctions() {
        return auctionItemMapper.selectEndingAuctions();
    }

    /**
     * 参与竞拍
     */
    @Override
    @Transactional
    public int placeBid(Long id, BigDecimal price) {
        // 获取拍卖信息
        AuctionItem auction = auctionItemMapper.selectAuctionItemById(id);
        if (auction == null || auction.getStatus() != 1) {
            throw new RuntimeException("拍卖不存在或未在进行中");
        }

        // 检查出价是否有效
        if (price.compareTo(auction.getCurrentPrice()) <= 0) {
            throw new RuntimeException("出价必须高于当前价格");
        }

        // 创建竞拍记录
        AuctionRecord record = new AuctionRecord();
        record.setAuctionId(id);
        record.setUserId(SecurityUtils.getUserId());
        record.setBidPrice(price);
        record.setCreateTime(DateUtils.getNowDate());
        auctionRecordMapper.insertAuctionRecord(record);

        // 更新当前价格
        auction.setCurrentPrice(price);
        return auctionItemMapper.updateAuctionItem(auction);
    }

    /**
     * 设置拍卖提醒
     */
    @Override
    public int setAuctionReminder(Long id) {
        // 获取拍卖信息
        AuctionItem auction = auctionItemMapper.selectAuctionItemById(id);
        if (auction == null || auction.getStatus() != 0) {
            throw new RuntimeException("拍卖不存在或已开始");
        }

        // TODO: 实现提醒功能，可以通过WebSocket、短信或邮件等方式
        // 这里先返回成功
        return 1;
    }

    /**
     * 获取拍卖历史记录
     */
    @Override
    public List<AuctionRecord> getAuctionHistory(Long id) {
        return auctionRecordMapper.selectAuctionRecordsByAuctionId(id);
    }
} 